package com.chinatechstar.component.commons.controller;

import com.chinatechstar.component.commons.supports.PageData;
import com.chinatechstar.component.commons.utils.EncryptUtil;
import com.chinatechstar.component.commons.utils.ServletUtils;
import com.chinatechstar.component.commons.utils.UuidUtil;

import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @ClassName:BaseController
 * @功能：通用Controller
 * @author：wlei
 * @日期：2021/1/6-9:42 下午
 **/
public class BaseController {
    /**
     * new PageData对象
     *
     * @return
     */
    public PageData getPageData() {

        HttpServletRequest request = getRequest();

        // 获取当前登录用户的角色
        String roleCode = request.getHeader("rolecode");
        String tid = request.getHeader("tid");
        // 解密tid
        try {
            tid = EncryptUtil.aesDecrypt(tid);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        if (StringUtils.isNotBlank(roleCode)) {
            String[] rawRoleCode = roleCode.split(",");
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < rawRoleCode.length; i++) {
                String tmp = StringUtils.strip(StringUtils.strip(rawRoleCode[i], "[]"), "\"");
                sb.append(tmp);
            }
            roleCode = sb.toString();
        }
        // 获取当前登录用户的用户名
        Authentication authentication = SecurityContextHolder
            .getContext()
            .getAuthentication();
        String userName = authentication.getName();

        PageData pageData = new PageData(request);
        pageData.put("roleCode", roleCode);
        pageData.put("loginuser", userName);
        // 如果userId为空,则赋空值
        pageData.put("userId", tid == null ? "" : tid);

        return pageData;
    }

    /**
     * 当前登录用户的id
     *
     * @param pageData
     * @return
     */
    public String getLoginUserId(PageData pageData) {
        String userid = (String) pageData.get("userId");
        return userid;
    }

    /**
     * 当前登录用户的角色
     *
     * @param pageData
     * @return
     */
    public String getLoginUserRoleCode(PageData pageData) {
        String userid = (String) pageData.get("roleCode");
        return userid;
    }


    /**
     * 得到request对象
     *
     * @return
     */
    public HttpServletRequest getRequest() {
        HttpServletRequest request = ServletUtils.getRequest();
        return request;
    }

    /**
     * 生成uuid
     *
     * @return
     */
    public String get32UUID() {
        return UuidUtil.get32UUID();
    }

}
